package product;

import java.util.HashSet;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MarketCount {

	/**统计每个省份农产品市场数
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		if (args.length!=2) {
			System.err.println("path err!");
			System.exit(-1);
		}
		Job job=new Job(new Configuration(),"prouductMark");
		job.setJarByClass(MarketCount.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		job.setMapperClass(pmMaps.class);
		job.setReducerClass(pmReduces.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		job.waitForCompletion(true);
	}
	public static class pmMaps extends Mapper<LongWritable, Text, Text, Text>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text, Text>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length==6) {
				String market = lines[3].trim();
				String province = lines[4].trim();
				context.write(new Text(province),new Text(market));
			}
		};
	}
	public static class pmReduces extends Reducer<Text,Text,Text,IntWritable>{
		
		protected void reduce(Text k2, java.lang.Iterable<Text> values, org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			HashSet<String> set=new HashSet<String>();
			for (Text value : values) {
				set.add(value.toString());//将农产品市场添加到Hashset集合。通过其本身的去重功能去重
			}
			context.write(k2, new IntWritable(set.size()));//hashset的长度就是每个省份农产品市场的数量
		};
	}
}
